package com.homework.reflect.bean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author nmm
 * @date 2024-03-2024/3/27
 * @deriction njm......
 */
public class BeanUtil {
    /**
     * @description 用于设置某个实例的具体属性值
     * @param  bean: clazz实例,String propertyName 属性名,Object value 要设置的值
     */
  public static void setProperty(Object bean, String propertyName, Object value) {
      try {
          Class<?> clazz = bean.getClass();
          Field setField = clazz.getDeclaredField(propertyName);
          setField.setAccessible(true);
          setField.set(bean,value);
      } catch (Exception e) {
           throw  new RuntimeException("未找到"+propertyName+"属性");
      }
  }


    /**
     *
     *@description 用于获取某个实例的具体属性值
     * @param  bean: clazz实例,String propertyName 要获取值的属性名
     * @return  具体属性值
     */
  public static Object getProperty(Object bean, String propertyName){
      Class<?> clazz = bean.getClass();
      try {
          Field declaredField = clazz.getDeclaredField(propertyName);
          declaredField.setAccessible(true);
          System.out.println(declaredField);
          return declaredField.get(bean);
      } catch (Exception e) {
          System.out.println("没有找到"+propertyName+"属性");
          return false;
      }
  }


    /**
     *
     *@description 用于获取某个实例的具体属性值
     * @param  source: 要copy属性值的class实例,target:要赋值的class实例
     */
  public static void copyProperties(Object source, Object target){
      Class<?> clazz = source.getClass();
      Class<?> clazz2 = target.getClass();//获取class实例
      try {
          if (clazz==clazz2){//判断是否是同一个Class
              Field[] declaredFields = clazz.getDeclaredFields();
              for (int i = 0; i < declaredFields.length; i++) {
                      Field allgetField = clazz.getDeclaredField(declaredFields[i].getName());//拿到第一个class实例的所有属性
                      allgetField.setAccessible(true);//设置为属性可访问为true
                      Object value = allgetField.get(source);//调用get方法拿到第一个实例参数值

                      Field allsetField = clazz2.getDeclaredField(declaredFields[i].getName());//拿到第二个class实例的所有属性
                      allsetField.setAccessible(true);//设置为属性可访问为true
                      allsetField.set(target,value);//调用set方法将第一个实例的值赋给目标实例(target)
              }
          }else {
             throw  new RuntimeException("不是同一个class实例");
          }
      } catch (Exception e) {
          e.printStackTrace();
      }
  }

}